package com.ecology.str;

public class DistanceBetweenSameChar {
    /**
     * 细瘦六道木,致危因子：生境退化或丧失；
     * 计算随机字符串中，如果有相同的字符，计算相同字符之间的距离，找出距离最大的
     * 例如：affa输出2；affaa输出3；ab输出-1，ff输出0
     * 脚印：双重for简单
     * 试试：lastIndexOf内部是while
     * @see com.ecology.str.TestString#test_distance_between_same_char
     */
    public static int distanceBetweenSameChar(String str) {
//        return withLastIndexOf(str);
//        return withDoubleFor(str);
        return withDoublePointer(str);
    }

    private static int withDoublePointer(String str) {
        if (null == str || str.length() < 1) {
            return -1;
        }
        int len = str.length();
        int maxVal = -1;
        int left = 0;
        int right = 1;
        while (right < len) {
            String lChar = str.substring(left, left + 1);
            String rChar = str.substring(right, right + 1);
            if (lChar.equals(rChar)) {
                maxVal = Math.max(maxVal, right - left - 1);
            }
            ++right;
            if (right > len - 1 && left + 1 < len) {
                ++left;
                right = left + 1;
            }
        }
        return maxVal;
    }


    private static int withDoubleFor(String str) {
        if (null == str || str.length() < 1) {
            return -1;
        }
        int len = str.length();
        int maxVal = -1;
        for (int i = 0; i < len; i++) {
            String iChar = str.substring(i, i + 1);
            int count = 0;
            for (int j = i+1; j < len; j++) {
                String jChar = str.substring(j, j + 1);
                if (iChar.equals(jChar)) {
                    if (count > maxVal) {
                        maxVal = count;
                    }
                }
                ++count;
            }
        }
        return maxVal;
    }

    private static int withLastIndexOf(String str) {
        if (null == str || str.length() < 1) {
            return -1;
        }
        int len = str.length();
        int maxVal = 0;
        for (int i = 0; i < len; i++) {
            String c = str.substring(i, i + 1);
            int lastIndex = str.lastIndexOf(c);
            if (lastIndex == -1) {
                continue;
            }
            int dis = lastIndex - i;
            if (dis > maxVal) {
                maxVal = dis;
            }
        }
        return maxVal - 1;
    }
}
